const {
  default: DPagination
} = require("../../../utils/DPagination");
const {
  getProjectNameLang
} = require("../common");
var location = require("../../../mybehaviors/location/location");
import util from "../../../utils/util";


// packageH/project_verification/MyProject/MyProject.js
const App = getApp();
const GetUnUseProjectUrl = App.getNetAddresss("plugin.store-projects.frontend.project-order.get-un-finish-list");
const GetUsedProjectUrl = App.getNetAddresss("plugin.store-projects.frontend.project-order.get-finish-list");
const ProjectsPagination = new DPagination("projects");
let Location = null;
Page({
  behaviors: [location],
  /**
   * 页面的初始数据
   */
  data: {
    currentShowPageTab: "0",
    projects: {},
    projectCount: 0,
    projectNameLang: getProjectNameLang(),
    showGivePop: false,
    giveInfo: {},
    giveUserId: '',
    giveNum: '',
    nickname: "",
    errorFlag: false,
    errorMsg: '',
    timeStyle: "0",
    addressValue: "",
    Location: {},
    imgPath: App.globalData.imgPath,
    // 预约弹窗
    showAppointment: false,
    // 预约选择门店弹窗
    showAppointment_Store: false,
    Appointment_Store: {
      page: 1,
      last_page: 0,
      keyword: '',
      radio: '',
      list: [],
      project_id: '',
      timeList: [],
      selectTime: '',
      DaySelect: new Date()
    },
    // 预约选择预约时间
    showAppointment_Time: false,
    showAppointment_Time_select: false,
    minDate: new Date().getTime(),
    maxDate: new Date(2025, 10, 1),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    if (options.Location) {
      let Location = JSON.parse(options.Location);
      this.setData({
        Location
      });
    }
    this._getLocation((res, point) => {
      Location = {
        point: point
      };
      this.getProjects();
    });

    ProjectsPagination.bind(this);
    this.getUserBaseInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.initAppointment_Store();
    let maxYear = new Date().getFullYear() + 5;
    this.setData({
      maxDate: new Date(maxYear, 1, 1).getTime()
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    ProjectsPagination.clean();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    ProjectsPagination.clean();
    this.getProjects();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getProjects();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  switchPageTabs({
    detail: {
      name
    }
  }) {
    this.setData({
      currentShowPageTab: name,
    });
    ProjectsPagination.clean();
    this.getProjects();
  },
  timeSort({
    currentTarget: {
      dataset: {
        val
      }
    }
  }) {
    let {
      timeStyle
    } = this.data;
    if (val === true) {
      timeStyle = timeStyle == 2 ? 3 : 2;
    } else {
      timeStyle = timeStyle == 0 ? 1 : 0;
    }
    this.setData({
      timeStyle
    });
    ProjectsPagination.clean();
    this.getProjects();
  },
  getProjects() {
    if (ProjectsPagination.loading || ProjectsPagination.finished) {
      return;
    }
    ProjectsPagination.loading = true;
    let url = GetUnUseProjectUrl;
    let point = App.qqMapTransBMap(parseFloat(Location.point.lng), parseFloat(Location.point.lat));
    let data = {
      page: ProjectsPagination.loadPage,
      lat: point.lat,
      lng: point.lng,
    };
    let loct = this.data.Location;
    if (Object.keys(loct).length > 0) {
      data.lat = loct.latitude;
      data.lng = loct.longitude;
      this.setData({
        addressValue: loct.message
      });
    } else {
      this.setData({
        addressValue: Location.address
      });
    }
    if (this.data.currentShowPageTab === "1") {
      url = GetUsedProjectUrl;
    } else {
      data.orderby = this.data.timeStyle;
    }
    wx.showLoading();
    App._getNetWork({
      url,
      data,
      success: ({
        data: {
          data: response,
          result,
          msg
        }
      }) => {
        ProjectsPagination.loading = false;
        wx.stopPullDownRefresh();
        wx.hideLoading();
        if (result == 0) {
          wx.showToast({
            title: msg,
            icon: "none",
          });
          return;
        }
        if (response.current_page == response.last_page || response.data.length < response.per_page) {
          ProjectsPagination.finished = true;
        }
        ProjectsPagination.push(response.data);
        this.setData({
          projectCount: ProjectsPagination.length,
        });
      },
    });
  },
  getUserBaseInfo() {
    const url = App.getNetAddresss("plugin.store-projects.frontend.index.get-base-info");
    App._getNetWork({
      url,
      data: {},
      success: ({
        data: {
          data
        }
      }) => {
        this.setData({
          hide_store: data.hide_store
        });
      },
    });
  },

  tapBtnGive(event) {
    let obj = event.currentTarget.dataset.item;
    this.setData({
      showGivePop: true,
      giveInfo: obj
    });
  },
  tolink(event) {
    console.log(event)
    let urls = event.currentTarget.dataset.url;
    wx.navigateTo({
      url: urls,
    })
  },
  // 关闭弹框
  closeGivePop() {
    this.setData({
      showGivePop: false,
    });
  },
  // 确定赠送
  giveProject() {
    if (!this.data.giveUserId) {
      this.setData({
        errorFlag: true,
        errorMsg: '请输入用户'
      });
      return;
    }
    if (this.data.errorFlag) {
      this.setData({
        errorMsg: '查无此用户',
        errorFlag: true
      });
      return;
    }

    if (!this.data.giveNum) {
      this.setData({
        errorNum: '转增次数不能为空'
      });
      return;
    }
    if (this.data.giveInfo.rest_count < this.data.giveNum) {
      this.setData({
        errorNum: '输入转赠次数大于拥有的次数'
      });
      return;
    }

    let urlStr = App.getNetAddresss("plugin.store-projects.frontend.project-order.transfer");
    App._getNetWork({
      url: urlStr,
      data: {
        id: this.data.giveInfo.id,
        transfer_uid: this.data.giveUserId,
        transfer_count: this.data.giveNum
      },
      success: (resdata) => {
        let res = resdata.data;
        console.log(res.msg);
        App.tips(res.msg);
        if (res.result == 1) {
          this.closeGivePop();
          ProjectsPagination.clean();
          this.getProjects();
        }

      }
    });
  },

  throttleFn(evt) {
    let uid = evt.detail;
    this.data.giveUserId = uid;
    this.data.errorFlag = true;
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
    }
    this.timeoutId = setTimeout(() => {
      this.searchUser(uid);
    }, 1000);
  },
  searchUser(uid) {
    let urlStr = App.getNetAddresss("member.member.memberInfo");
    console.log(urlStr);
    App._getNetWork({
      url: urlStr,
      data: {
        uid
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1 && res.data != null) {
          this.setData({
            nickname: res.data.nickname,
            errorFlag: false,
            giveUserId: uid
          });
        } else {
          this.setData({
            errorFlag: true,
            errorMsg: '查无此用户'
          });
        }

      },
      fail: () => {
        this.setData({
          giveUserId: '',
          errorFlag: true,
          errorMsg: '查无此用户'
        });
      }
    });
  },
  changeNumInput(event) {
    console.log(event);
    let num = this.data.giveNum;
    let errorNum = '';
    if (num <= 0) {
      errorNum = "转增次数不能为空";
    } else if (this.data.giveInfo.rest_count < num) {
      errorNum = "输入转赠次数大于拥有的次数";
    }
    this.setData({
      errorNum
    });
  },
  onClickLeft1() {
    this.setData({
      showAppointment_Store: false,
    })
    if (!this.data.Appointment_Store.radio) {
      this.setData({
        'Appointment_Store.radio': []
      })
    }
    this.setData({
      'Appointment_Store.page': 1,
      'Appointment_Store.last_page': 0
    })
  },
  onClickLeft() {
    this.setData({
      showAppointment_Time: false
    })
  },
  onClickRight() {
    this.setData({
      showAppointment_Time: false
    })
  },
  onChange_search(e) {
    this.setData({
      'Appointment_Store.keyword': e.detail,
    });
  },
  onSearch(e) {
    console.log(e)
    this.setData({
      'Appointment_Store.radio': [],
      'Appointment_Store.page': 1,
      'Appointment_Store.last_page': 0,
      'Appointment_Store.list': [],
    })
    this.showAppointmentOpen();
  },
  onClickRight1() {
    this.setData({
      showAppointment_Store: false
    })
    if (this.data.Appointment_Store.radio.length == 0) {
      this.setData({
        'Appointment_Store.radio': []
      })
    }
  },
  initAppointment_Store() {
    this.setData({
      'Appointment_Store.page': 1,
      'Appointment_Store.last_page': 0,
      'Appointment_Store.keyword': '',
      'Appointment_Store.radio': [],
      'Appointment_Store.list': [],
      'Appointment_Store.project_id': "",
      'Appointment_Store.timeList': [],
      'Appointment_Store.selectTime': "",
      'Appointment_Store.DaySelect': new Date().getTime(),
      showAppointment_Time: false,
      showAppointment_Time_select: false,
      showAppointment_Store: false
    })
  },
  showAppointment_Store_open() {
    this.setData({
      showAppointment_Store: true,
      'Appointment_Store.keyword': ''
    })
  },
  showAppointment_Time_select_open() {
    this.setData({
      showAppointment_Time_select: true
    })
  },
  async showAppointment_TimeOpen() {
    let now = Date.parse(this.data.Appointment_Store.DaySelect) / 1000;
    now = this.timestampToTime(now);
    if (!this.data.Appointment_Store.radio) return app.tips('请先选择门店');
    let json = {
      plugin_order_id: this.data.Appointment_Store.project_id,
      store_id: String(this.data.Appointment_Store.radio),
      day: now
    }
    let {
      data
    } = await App._postNetWork({
      url: App.getNetAddresss("plugin.store-projects.frontend.expect.expectTimeList"),
      data: json,
    })
    if (data.result) {
      if (data.data.length > 0) {
        this.setData({
          showAppointment_Time: true,
          timeList: data.data
        })
      }
    } else {
      App.tips(data.msg)
      this.setData({
        'Appointment_Store.selectTime': "",
        timeList: []
      })
    }
  },
  timestampToTime: function (timestamp) {
    if (!Number(timestamp) || timestamp == "") {
      return "";
    }
    let date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear();
    let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1);
    let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate());
    return Y + M + D;
  },
  tapStore(e) {
    let item = e.currentTarget.dataset.item;
    if (this.data.Appointment_Store.radio == item.id) {
      this.setData({
        'Appointment_Store.radio': []
      })
      return
    }
    this.setData({
      'Appointment_Store.radio': [String(item.id)]
    })
    console.log(this.data.Appointment_Store.radio)
    if (item.expect_days > 0) {
      this.setData({
        maxDate: new Date(new Date().getTime() + (item.expect_days * 24 * 60 * 60 * 1000)).getTime()
      })
    }
  },
  async showAppointmentOpen(e) {
    let app = App;
    let project_id;
    if (e && e.currentTarget) {
      let {
        item
      } = e.currentTarget.dataset;
      project_id = this.data.Appointment_Store?.project_id ? this.data.Appointment_Store.project_id : item.id;
      this.setData({
        'Appointment_Store.project_id': project_id
      })
    } else {
      project_id = this.data.Appointment_Store?.project_id
    }


    let json = {
      plugin_order_id: project_id,
      store_name: this.data.Appointment_Store.keyword
    };
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("plugin.store-projects.frontend.expect.expectData"),
      data: json,
    })
    if (data.result) {
      this.setData({
        'Appointment_Store.list': data.data.store_list.data,
        'Appointment_Store.page': 1,
        'Appointment_Store.last_page': data.data.store_list.last_page,
        showAppointment: true
      })
    } else {
      app.tips(data.msg);
    }
  },
  time_cancel() {
    this.setData({
      showAppointment_Time_select: false
    })
  },
  async time_confirm(e) {
    this.setData({
      'Appointment_Store.DaySelect': e.detail
    })
    await this.showAppointment_TimeOpen();
    this.setData({
      showAppointment_Time_select: false
    })
  },
  tapStoreTime(e) {
    let {
      item
    } = e.currentTarget.dataset;
    if (item.is_full == 1) return;
    if (item.id == this.data.Appointment_Store.selectTime) {
      this.setData({
        'Appointment_Store.selectTime': ''
      })
      return
    }
    this.setData({
      'Appointment_Store.selectTime': item.id
    })
    console.log(this.data.Appointment_Store.selectTime)
  },
  showAppointment_Tap_Cancel() {
    this.setData({
      'Appointment_Store.radio': '',
      'Appointment_Store.selectTime': "",
      'Appointment_Store.page': 1,
      'Appointment_Store.last_page': 0,
      'Appointment_Store.project_id': '',
      showAppointment: false
    })
  },
  async showAppointment_Tap_confirm() {
    if (this.data.Appointment_Store.radio.length <= 0) {
      App.tips('请选择门店')
      return
    }
    if (!this.data.Appointment_Store.selectTime) {
      App.tips('请选择预约时间')
      return
    }
    let json = {
      plugin_order_id: this.data.Appointment_Store.project_id,
      expect_set_id: this.data.Appointment_Store.selectTime,
      store_id: String(this.data.Appointment_Store.radio),
      day: util.formatTimeTwo((this.data.Appointment_Store.DaySelect / 1000), 'YMD')
    };
    let {
      data
    } = await App._postNetWork({
      url: App.getNetAddresss("plugin.store-projects.frontend.expect.expect"),
      data: json,
    })
    if (data.result) {
      App.tips(data.msg);
      this.setData({
        showAppointment: false
      })
    } else {
      App.tips(data.msg)
    }
  },
  btnVerUser(e) {
    let {
      item
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/packageH/project_verification/WriteOffRecord/WriteOffRecord?type=used&project_name=' + item.project_title,
    })
  },
  btnUsere(e) {
    let {
      item
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/packageH/project_verification/WriteOff/WriteOff?project_order_id=' + item.id,
    })
  }
});